package com.lyd.sweet.feign.decoder;

import com.lyd.sweet.exception.SweetBasicException;
import com.lyd.sweet.model.ServiceStatus;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.json.JacksonJsonParser;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Feign统一异常处理解码器
 * 用于处理SweetBoot定义的标准业务异常返回消息
 * @author 木木
 */
@Slf4j
public class FeignErrorDecoder extends ErrorDecoder.Default {

    private final String HEAD_KEY = "head";

    private final String CODE_KEY = "code";

    private final String MESSAGE_KEY = "message";

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String bodyJson = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            JacksonJsonParser jacksonJsonParser = new JacksonJsonParser();
            Map<String, Object> errorInfo = jacksonJsonParser.parseMap(bodyJson);
            // 目前根据返回的JSON字符串 判断是否带head字段 如果带head字段说明是SweetBoot定义的标准业务返回(ResponseObject)
            // 解析JSON字符串 构建 SweetBasicException对象 返回给调用的服务
            if (errorInfo.containsKey(HEAD_KEY)) {
                Map<String, Object> headMap = (Map<String, Object>) errorInfo.get(HEAD_KEY);
                String code = headMap.get(CODE_KEY).toString();
                String message = headMap.get(MESSAGE_KEY).toString();
                ServiceStatus serviceStatus = new ServiceStatus(code, message);
                return new SweetBasicException(serviceStatus, message);
            } else {
                // 如果不是SweetBasicException 则用默认异常类包装信息返回
                return super.decode(methodKey, response);
            }
        } catch (Exception e) {
            log.warn(e.getMessage());
            return super.decode(methodKey, response);
        }
    }
}
